from pojo.results import Result
from utils.log import logger
from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Request
from langchain.text_splitter import RecursiveCharacterTextSplitter
from utils.single_generate import DesignSingle
from utils.multi_generate import DesignMutiple
from utils.judge_generate import DesignJudge
async def question_generate_imp(file,type,complexity):
    """

    :param file: 待生成题目的文档
    :param type: 题目类别
    :param complexity: 题目难度
    :return: 生成的json数组
    """
    try:
        text = await file.read()          # 读取文件内容（字节流）
        text = text.decode("utf-8")            # 将字节流解码为字符串
    except Exception:
        Result(400, '文件读取失败', None).to_dict()
        raise HTTPException(status_code=400, detail='文件读取失败')

    # 建立的文本递归切分器
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=16384,
        chunk_overlap=1024,
        #定义如何切分的函数，按照字符数量进行切分
        length_function=len,
        keep_separator=True,  # 保留分隔符（默认保留在末尾）
        separators=["\n\n", "\n", " ", ""]

    )
    # 切分完毕的文本
    docs = text_splitter.split_text(text)
    logger.info(f"切分完毕之后的list数组长度为：{len(docs)}")
    data = []
    match type :
        case 1:
            for item in docs:
                jsonlist = DesignSingle(item, complexity)
                data.extend(jsonlist)
        case 2:
            for item in docs:
                jsonlist = DesignMutiple(item, complexity)
                data.extend(jsonlist)
        case 3:
            for item in docs:
                jsonlist = DesignJudge(item, complexity)
                data.extend(jsonlist)

    return data
